<template>
    <el-card style="max-width: 100%">
        <!-- 添加按钮 -->
        <el-button type="primary" icon="Plus" @click="addTrademark">添加品牌</el-button>
        <!-- 表格数据 -->
        <!-- table:---border:可以设置表格纵向是否有边框
             table-column:---label:某一个列表 ---width:设置这列宽度 ---align:设置这一列对齐方式    
            -->
        <el-table :data="trademarkArr" style="margin: 10px 10px;" border>
            <el-table-column label="序号" prop="date" width="80px" type="index" align="center" />
            <el-table-column label="品牌名称" prop="tmName" />
            <el-table-column label="品牌LOGO">
                <template #="{ row, $index }">
                    <img :src="row.logoUrl" style="width:100px;height: 100px;" />
                </template>
            </el-table-column>
            <el-table-column label="品牌操作">
                <template #="{ row, $index }">
                    <el-button type="primary" icon="Edit" @click="updateTrademark(row)" />
                    <el-popconfirm :title="`你确定要删除【${row.tmName}】吗?`" icon="Delete" width="250px"
                        @confirm="deleteTrademark(row.id)">
                        <template #reference>
                            <el-button type="danger" icon="Delete" />
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器组件
                pagination
                   v-model:current-page:设置分页器当前页码
                   v-model:page-size:设置每一个展示数据条数
                   page-sizes:用于设置下拉菜单数据
                   background:设置分页器按钮的背景颜色
                   layout:可以设置分页器六个子组件布局调整
            -->
        <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[5, 10, 15, 20]" background
            layout="prev, pager, next, jumper,->,sizes,total" :total="total" @size-change="pageSizesChange"
            @current-change="getHasTrademark" />

    </el-card>

    <!-- 新增编辑弹窗 -->
    <!-- 对话框组件:在添加品牌与修改已有品牌的业务时候使用结构 -->
    <!-- 
            v-model:属性用户控制对话框的显示与隐藏的 true显示 false隐藏
             title:设置对话框左上角标题
        -->
    <el-dialog v-model="addOrUpdateDialogVisible" title="添加品牌">
        <el-form :model="trademarkFromData" style="width: 80%;" :rules="rules" ref="formRef">
            <el-form-item label="品牌名称" label-width="100px" prop="tmName">
                <el-input v-model="trademarkFromData.tmName" placeholder="请输入品牌名称" />
            </el-form-item>
            <el-form-item label="品牌Logo" label-width="100px" prop="logoUrl">
                <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
                <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="trademarkFromData.logoUrl" :src="trademarkFromData.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script setup lang='ts'>
import { ref, reactive, onMounted, nextTick } from 'vue'
import TrademarkApi from '@/api/product/trademark'
import { TradeMark, TradeMarkResponseData, Records } from '@/api/product/trademark/type'
import { ElMessage, type UploadProps } from 'element-plus'

//存储已有品牌列表的数据
let trademarkArr = ref<Records>([])
//当前页数
let pageNo = ref<number>(1)
//页大小
let limit = ref<number>(5)
//总记录数
let total = ref<number>(0)
//控制对话框显示与隐藏弹窗
let addOrUpdateDialogVisible = ref<boolean>(false)
//收集保存品牌数据
let trademarkFromData = reactive<TradeMark>({
    logoUrl: '',
    tmName: ''
})
//获取弹窗el-form组件实例
let formRef = ref()

//获取已有品牌的接口封装为一个函数:在任何情况下向获取数据,调用次函数即可
const getHasTrademark = async (pager = 1) => { //默认传参pager
    //当前页码
    pageNo.value = pager;
    let result: TradeMarkResponseData = await TrademarkApi.reqHasTrademark(pageNo.value, limit.value)
    // console.log("11", result)
    if (result.code == 200) {
        total.value = result.data.total
        trademarkArr.value = result.data.records
    }


}
//组件挂载完成执行
onMounted(() => {
    getHasTrademark()
})

//下拉页大小改变时触发
//这个自定义事件,分页器组件会将下拉菜单选中数据返回
const pageSizesChange = (size: number) => {
    //页大小
    limit.value = size
    //页码归1
    pageNo.value = 1
    getHasTrademark()
}

//添加品牌
const addTrademark = () => {
    //打开弹窗
    addOrUpdateDialogVisible.value = true
    //清空收集数据
    trademarkFromData.id = 0
    trademarkFromData.logoUrl = ''
    trademarkFromData.tmName = ''


    //nextTick: 它允许你在下一次 DOM 更新周期结束之后执行代码
    nextTick(() => {
        formRef.value.clearValidate("tmName")
        formRef.value.clearValidate("logoUrl")
    })
}

//编辑品牌
const updateTrademark = (row: TradeMark) => {
    // console.log(row)
    //打开弹窗
    addOrUpdateDialogVisible.value = true
    //第一种方式
    trademarkFromData.id = row.id
    trademarkFromData.tmName = row.tmName
    trademarkFromData.logoUrl = row.logoUrl
    //第二种方式
    // Object.assign(trademarkFromData,row)

    //nextTick: 它允许你在下一次 DOM 更新周期结束之后执行代码
    nextTick(() => {
        formRef.value.clearValidate("tmName")
        formRef.value.clearValidate("logoUrl")
    })

}

//删除品牌
const deleteTrademark = async (id: number) => {
    // console.log(id)
    let result = await TrademarkApi.reqDeleteTrademark(id)
    if (result.code == 200) {
        ElMessage({
            type: 'success',
            message: '删除成功'
        })
        //刷新页面(当前记录大于1，留在当前页，记录数小于1，回到上一页)
        getHasTrademark(trademarkArr.value.length > 0 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage({
            type: 'error',
            message: '删除失败'
        })
    }
}

//取消
const cancel = () => {
    //关闭弹窗
    addOrUpdateDialogVisible.value = false
}

//确认
const confirm = async () => {
    // console.log("data", trademarkFromData)
    // console.log("formRef", formRef)
    await formRef.value.validate() //等待所有表单校验都通过才执行后面代码
    let result = await TrademarkApi.reqAddOrUpdateTrademark(trademarkFromData)
    if (result.code == 200) {
        ElMessage({
            type: "success",
            message: trademarkFromData.id ? '编辑成功' : '新增成功'
        })
        //刷新页面（编辑成功，跳转到当前页码，新增成功跳转到第一页）
        getHasTrademark(trademarkFromData.id ? pageNo.value : 1)
    } else {
        ElMessage({
            type: 'error',
            message: trademarkFromData.id ? '编辑失败' : '新增失败'
        })
    }
    //关闭弹窗
    addOrUpdateDialogVisible.value = false


}

//上传文件之前的钩子，参数为上传的文件， 若返回false或者返回 Promise 且被 reject，则停止上传。
const beforeAvatarUpload: UploadProps['beforeUpload'] = (uploadFile) => {
    //要求:上传文件格式png|jpg|gif 4M
    // console.log(uploadFile)
    if (uploadFile.type == 'image/jpeg' || uploadFile.type == 'image/png' || uploadFile.type == 'image/gif') {
        if (uploadFile.size > 2 * 1024 * 1024) {
            ElMessage({
                type: 'error',
                message: '上传文件大小小于2M'
            })
            return false
        }
        return true
    } else {
        ElMessage({
            type: 'error',
            message: '上传文件格式务必PNG|JPG|GIF'
        })
        return false
    }
}

//上传图片成功回调
/**
 * 
 * @param response 
 * @param uploadFile 文件
 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    // console.log("uploadImg", response)
    if (response.code == 200) {
        trademarkFromData.logoUrl = response.data
    }
}

/** 表单校验 */
//校验品牌名称
const validateTmName = (rule: any, value: any, callback: any) => {
    /**
     * rule：即为校验规则对象
     * value：即为表单元素文本内容
     * callback 如果符合条件callBack放行通过即为,如果不符合条件callBack方法,注入错误提示信息
     */
    if (value.trim().length > 2) {
        callback()
    } else {
        callback(new Error("名牌名称不能少于两个字"))
    }
}
//检验品牌logo
const validateLogoUrl = (rule: any, value: any, callback: any) => {
    if (value) {
        callback();
    } else {
        callback(new Error('LOGO图片务必上传'))
    }
}

//校验规则
const rules = {
    tmName: [
        { required: true, trigger: 'blur', validator: validateTmName }
    ],
    logoUrl: [
        { required: true, validator: validateLogoUrl }
    ]
}


</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>